﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Windows.Threading;

namespace PersonaLibrary.ViewModel
{
	public abstract class BaseViewModel<TView> : DispatcherObject, INotifyPropertyChanged, IViewModel
		where TView : View.IView, new()
	{
		private View.IView _view;

		void View_Closed(object sender, EventArgs e)
		{
			OnClosed();
			Dispose();
		}

		protected virtual void OnClosed()
		{}

		public View.IView View
		{
			get
			{
				if (_view == null)
				{
					_view = new TView();
					OnViewCreated();
				}
				return _view;
			}
		}

		public App CurrentApplication
		{
			get
			{
				return (App) System.Windows.Application.Current;
			}
		}

		protected virtual void OnViewCreated()
		{
			_view.DataContext = this;
			_view.Closed += View_Closed;
		}

		protected void RisePropertyChanged(string propertyName)
		{
			if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
		}
		
		public event PropertyChangedEventHandler PropertyChanged;

		public virtual void Dispose()
		{
			GC.SuppressFinalize(this);
		}
	}
}
